/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ikkong.biz.controller;

import java.util.List;

import com.ikkong.biz.BizCst;
import com.ikkong.biz.service.TeacherDeptService;
import com.ikkong.biz.service.impl.TeacherDeptServiceImpl;
import com.ikkong.core.constant.ConstCache;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.toolbox.Conver;
import com.ikkong.core.toolbox.Record;
import com.ikkong.system.controller.base.AdminBaseController;
import com.ikkong.system.meta.intercept.DeptIntercept;
import com.ikkong.system.model.Dept;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;

/**
 * tb_teacher表默认1000以前留给老师部门来新增
 */
public class TeacherDeptController extends AdminBaseController{
	private static String LIST_SOURCE = "Dept.teacher_list";
	private static String BASE_PATH = "/biz/teacher_dept/";
	private static String CODE = "teacherDept";
	private static String PERFIX = "tfw_dept";

    private TeacherDeptService service = new TeacherDeptServiceImpl();


    public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "dept.html");
	}
	
	
	public void list() {
		Object gird = paginate(LIST_SOURCE);
        renderJson(gird);
	}
	
	public void add() {
		String id = getPara(0);
		if (StrKit.notBlank(id)) {
			setAttr("pId", id);
			setAttr("num", findLastNum(id));
		}
		setAttr("code", CODE);
		render(BASE_PATH + "dept_add.html");
	}
	
	public void edit() {
		String id = getPara(0);
		Dept Dept = Blade.create(Dept.class).findById(id);
		// important ,设置上级部门，保证在编辑的时候能够取到pid,在页面用value:pid能够取到值 
		setAttr("pid",Dept.getPid());
		setAttr("model", JsonKit.toJson(Dept));
		setAttr("code", CODE);
		render(BASE_PATH + "dept_edit.html");
	}

	public void view() {
		String id = getPara(0);
		Blade blade = Blade.create(Dept.class);
		Dept Dept = blade.findById(id);
		Dept parent = blade.findById(Dept.getPid());
		String pName = (null == parent) ? "" : parent.getSimplename();
		Record maps = Record.parse(Dept);
		maps.set("pName", pName);
		setAttr("model", JsonKit.toJson(maps));
		setAttr("code", CODE);
		render(BASE_PATH + "dept_view.html");
	}
	
	public void save() {
		Dept dept = mapping(PERFIX, Dept.class);
		dept.setType(BizCst.TEA_TYPE);
        if (dept.getPid()==null || dept.getPid().intValue() == 0){
            dept.setPid(BizCst.TOP_DEPT);
        }
        dept.setSimplename(dept.getFullname());
		boolean temp = Blade.create(Dept.class).save(dept);
        CacheKit.removeAll(ConstCache.TEACHER_DEPT_CACHE);
        if (temp) {
			CacheKit.removeAll(DEPT_CACHE);
			renderJson(success("新增成功"));
		} else {
			renderJson(error("新增失败"));
		}
	}

	public void update() {
		Dept dept = mapping(PERFIX, Dept.class);
		Dept oriDept =  service.findById(dept.getId());
        oriDept.setPid(dept.getPid());
        if (dept.getPid()==null || dept.getPid().intValue() == 0){
        	oriDept.setPid(BizCst.TOP_DEPT);
        }
        oriDept.setFullname(dept.getFullname());
        oriDept.setSimplename(dept.getFullname());
        oriDept.setNum(dept.getNum());
        oriDept.setTips(dept.getTips());
        
        oriDept.setVersion(oriDept.getVersion() + 1);
		boolean temp =  Blade.create(Dept.class).updateEveryCol(oriDept);
        CacheKit.removeAll(ConstCache.TEACHER_DEPT_CACHE);
        if (temp) {
			CacheKit.removeAll(DEPT_CACHE);
			renderJson(success("修改成功"));
		} else {
			renderJson(error("修改失败"));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = Blade.create(Dept.class).deleteByIds(ids);
        CacheKit.removeAll(ConstCache.TEACHER_DEPT_CACHE);
        if (cnt > 0) {
			CacheKit.removeAll(DEPT_CACHE);
			renderJson(success("删除成功!"));
		} else {
			renderJson(error("删除失败!"));
		}
	}
	
	private int findLastNum(String id){
		try{
			Blade blade = Blade.create(Dept.class);
			Dept dept = blade.findFirstBy("pId = #{pId} order by num desc", Record.create().set("pId", id));
			return dept.getNum() + 1;
		}
		catch(Exception ex){
			return 1;
		}
	}

    public void toImport(){
        setAttr("code", CODE);
        render(BASE_PATH + "dept_import.html");
    }

    public void doImport(){
		List<UploadFile> flist = this.getFiles("/temp", 1024*1024*50);
		if(flist.size()>0){
			UploadFile uf=flist.get(0);
			String result = service.doImport(uf.getFile());
			renderJson(success(result));
		}
    }
}
